package com.example.statistics.ui.product

import android.os.Bundle
import android.view.View
import android.widget.ImageView
import com.example.statistics.R
import com.example.statistics.bean.ProductBean
import com.example.statistics.bean.ProductTreeBean
import com.example.statistics.common.BaseActivity
import com.example.statistics.net.UrlConfig
import com.example.statistics.net.callback.DataDialogHttpCallback
import com.example.statistics.utils.Constants
import com.jhj.httplibrary.HttpCall
import com.jhj.slimadapter.SlimAdapter
import com.jhj.slimadapter.itemdecoration.LineItemDecoration
import com.example.statistics.ex.glide
import kotlinx.android.synthetic.main.activity_recyclerview_refresh.*
import kotlinx.android.synthetic.main.layout_search_bar.*
import org.jetbrains.anko.dip
import org.jetbrains.anko.leftPadding
import org.jetbrains.anko.sdk27.coroutines.onClick
import org.jetbrains.anko.startActivity

class ProductTreeActivity : BaseActivity() {

    val adapter = SlimAdapter.creator()

    override val title: String
        get() = ""


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_recyclerview_refresh)
        layout_search_bar.visibility = View.GONE
        topBarOtherImage {
            startActivity<ProductInfoListActivity>()
        }
        initAdapter(adapter)
        refresh(adapter)

    }

    private fun refresh(adapter: SlimAdapter) {
        HttpCall.get(UrlConfig.PRODUCT_INFO_LIST)
                .enqueue(object : DataDialogHttpCallback<List<ProductBean>>(this) {
                    override fun onSuccess(data: List<ProductBean>?, resultType: ResultType) {
                        val tree = listToTree(data.orEmpty())
                        adapter.setDataList(tree)
                    }
                })
    }

    private fun initAdapter(adapter: SlimAdapter) {
        recyclerView.addItemDecoration(LineItemDecoration())
        adapter.registerTree<ProductTreeBean>(R.layout.tree_item_goods_root, R.layout.tree_item_goods_node) { injector, bean, position ->
            val arrow = injector.getView<ImageView>(R.id.iv_arrow)
            val imageView = injector.getView<ImageView>(R.id.image_view)
            injector.text(R.id.tv_title, bean.name)
                    .with<ImageView>(R.id.iv_arrow) {
                        it.glide(R.drawable.ic__eye_black)
                        it.onClick {
                            startActivity<ProductInfoEditActivity>()
                        }
                    }
                    .with<ImageView>(R.id.image_view) {
                        if (bean.isRoot) {
                            it.glide(R.drawable.ic_tree_node_close)
                        } else {
                            it.glide(R.drawable.ic_tree_node)
                        }
                    }
                    .with {
                        it.leftPadding = dip(20) * bean.itemLevels
                    }
                    .clicked {
                        itemClickResponse(bean,
                                itemClose = {
                                    imageView.glide(R.drawable.ic_tree_node_close)
                                },
                                itemExpend = {
                                    imageView.glide(R.drawable.ic_tree_root_expend)
                                },
                                itemNode = {
                                    startActivity<ProductInfoEditActivity>(Constants.ID to bean.id, Constants.TYPE to "猪副")

                                })
                    }
            /*injector.longClicked {
                val list = listOf("新增子级", "编辑", "删除")
                bottomSingleDialog(list = list) { doalog, str ->
                    when (str) {
                        "新增同级" -> {
                            val path = bean.path.substring(0, bean.path.lastIndexOf("/"))
                            ActivityResult.with(this@ProductTreeActivity)
                                    .targetActivity(GoodsActivity::class.java)
                                    .putInt("parentId", bean.parentId)
                                    .putString("parentName", bean.parentName)
                                    .putString(Constants.TITLE, title)
                                    .putString("path", path)
                                    .onResult {
                                        GlobalScope.launch {
                                            val treeBean =
                                                    it?.getSerializableExtra("data") as GoodsTreeBean
                                            treeBean.itemLevels = bean.itemLevels
                                            val current =
                                                    db.goodsDao().query(treeBean.name, bean.parentId)
                                            if (current != null) {
                                                treeBean.id = current.id
                                                treeBean.path = path + "/" + current.id
                                            }
                                            withContext(Dispatchers.Main) {
                                                adapter.addData(position + 1, treeBean)
                                                val parent = adapter.getDataList<GoodsTreeBean>()
                                                        .find { it.id == bean.parentId }
                                                parent?.getChildren()?.add(treeBean)
                                                val list =adapter.getDataList()
                                                adapter.setDataList(adapter.getDataList())
                                            }
                                        }
                                    }
                        }
                        "新增子级" -> {
                            ActivityResult.with(this@ProductTreeActivity)
                                    .targetActivity(GoodsActivity::class.java)
                                    .putInt("parentId", bean.id)
                                    .putString("parentName", bean.name)
                                    .putString("path", bean.path)
                                    .putString(Constants.TITLE, title)
                                    .onResult {
                                        refresh(adapter)
                                    }
                        }
                        "编辑" -> {
                            val path = bean.path.substring(0, bean.path.lastIndexOf("/"))
                            ActivityResult.with(this@GoodsTreeActivity)
                                    .targetActivity(GoodsActivity::class.java)
                                    .putInt("parentId", bean.parentId)
                                    .putString("parentName", bean.parentName)
                                    .putString(Constants.TITLE, title)
                                    .putString("path", path)
                                    .putSerializable("data", bean)
                                    .onResult {
                                        refresh(adapter)
                                    }
                        }
                        "查看" -> {
                            startActivity<GoodsDetailActivity>("data" to bean)
                        }
                        "删除" -> {
                            if (!bean.getChildren().isNullOrEmpty()) {
                                toast("有子级，不能删除")
                                return@bottomSingleDialog
                            }
                            GlobalScope.launch {
                                val db = DBHelper.db
                                GlobalScope.launch {
                                    db.goodsDao().delete(bean.id)
                                    withContext(Dispatchers.Main) {
                                        refresh(adapter)
                                    }
                                }

                            }
                        }
                    }

                }
                false
            }*/
        }
                .attachTo(recyclerView)
    }


    fun listToTree(list: List<ProductBean>): MutableList<ProductTreeBean> {
        val treeList = mutableListOf<ProductTreeBean>()
        list.forEach {
            if (treeList.filter { bean -> it.nation == bean.name }.isNullOrEmpty()) {
                val productTreeBean = ProductTreeBean()
                productTreeBean.id = it.id
                productTreeBean.name = it.nation
                productTreeBean.productType = it.productType
                productTreeBean.productNo = it.productNo
                productTreeBean.specification = it.specification
                productTreeBean.priceTrend = it.priceTrend
                productTreeBean.remark = it.remark
                productTreeBean.itemLevels = 1
                val child = getChildren(productTreeBean, list)
                treeList.add(child)
            }
        }
        //treeList.sortWith(compareBy({  }, { it.name }))
        return treeList
    }


    private fun getChildren(tree: ProductTreeBean, list: List<ProductBean>): ProductTreeBean {
        list.forEach {
            val bean = ProductTreeBean()
            if (it.company.isNotBlank()) {
                if (tree.itemLevels == 1 && tree.name == it.nation) {
                    bean.name = it.company
                    bean.itemLevels = 2
                } else if (tree.itemLevels == 2 && tree.name == it.company) {
                    bean.name = it.factoryNo
                    bean.itemLevels = 3
                } else if (tree.itemLevels == 3 && tree.name == it.factoryNo) {
                    bean.name = it.productName
                    bean.itemLevels = 4
                }
            } else {
                if (tree.itemLevels == 1 && tree.name == it.nation) {
                    bean.name = it.factoryNo
                    bean.itemLevels = 2
                } else if (tree.itemLevels == 2 && tree.name == it.factoryNo) {
                    bean.name = it.productName
                    bean.itemLevels = 3
                }
            }
            if (!bean.name.isNullOrEmpty()) {
                bean.id = it.id
                bean.productType = it.productType
                bean.productNo = it.productNo
                bean.specification = it.specification
                bean.priceTrend = it.priceTrend
                bean.remark = it.remark
                val childTree = getChildren(bean, list)
                if (tree.getChildren()?.filter { it.name == bean.name }.isNullOrEmpty()) {
                    if (tree.getChildren().isNullOrEmpty()) {
                        tree.isRoot = true
                        tree.setChildren(arrayListOf(childTree))
                    } else {
                        tree.getChildren()?.add(childTree)
                    }
                }
            }
        }
        return tree
    }
}